package array;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Jisheng Huang
 * @version 20250504
 */
public class NumOfEquiDominoPairs_1128 {
    /**
     * Create a Map to store the occurrence of the d[0] *10 + d[1] which
     * d[0] is the smallest number in each pair of dominoes
     * d[1] is the biggest number in each pair of dominoes
     * <p>
     * Loop through the whole dominoes and record the number of occurrence
     * <p>
     * Loop through the map and calculate the number of occurrence which is greater than 1
     *
     * @param dominoes the given 2d array
     * @return the number of equivalent pairs greater than 1
     */
    public static int numEquivDominoPairs(int[][] dominoes) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;

        for (int[] d : dominoes) {
            int cur = Math.min(d[0], d[1]) * 10 + Math.max(d[0], d[1]);

            map.put(cur, map.getOrDefault(cur, 0) + 1);
        }

        for (int v : map.values()) {
            res += v * (v - 1) / 2;
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] dominoes = {{1, 2}, {2, 1}, {3, 4}, {5, 6}};
        System.out.println(numEquivDominoPairs(dominoes));

        dominoes = new int[][]{{1, 2}, {1, 2}, {1, 1}, {1, 2}, {2, 2}};
        System.out.println(numEquivDominoPairs(dominoes));
    }
}
